import {
	config
} from '@/utils/config.js'

/*
isLoading: 是否显示加载图标
isJson： 是否启用Json提交格式
isAuth: 是否需要token
*/

let needLoadingRequestCount = 0

function showFullScreenLoading() {
	if (needLoadingRequestCount === 0) {
		uni.showLoading({
			title: "加载中",
			mask: true
		})
	}
	needLoadingRequestCount++
}

function hideFullScreenLoading() {
	if (needLoadingRequestCount <= 0) return
	needLoadingRequestCount--
	if (needLoadingRequestCount === 0) {
		uni.hideLoading()
	}
}
export default function(options, lose) {
	const token = uni.getStorageSync('token'); // 从缓存中获取token
	if (token || (options.isAuth === false)) {
		return requestContent(options, lose)
	} else {
		uni.redirectTo({
			url: "/pages/login/index"
		})
	}
}
// 封装请求方法，并向外暴露该方法
const requestContent = (options, lose) => {
	if (options.isLoading !== false) {
		showFullScreenLoading()
	}
	// 解构请求头参数
	// let header = {...options.header};
	// 当前请求不是登录时请求，在header中加上后端返回的token
	const token = uni.getStorageSync('token');
	const header = {
		"Content-Type": !options.isJson ? "application/x-www-form-urlencoded" : "application/json",
		"token": token || ''
	}
	const data = !options.isJson ? {
		...options.data
	} : options.data
	return new Promise((resolve, reject) => {
		uni.request({
			url: config.BASE_API + options.url,
			method: options.method || 'POST',
			data: data || {},
			header,
			success: (response) => {
				const res = response.data
				if (res.code !== 200) {
					switch (res.code) {
						// 401: token失效或不存在
						case 101:
							if (options.isLoading !== false) {
								hideFullScreenLoading()
							}
							uni.removeStorageSync('token');
							if (!lose) {
								uni.reLaunch({
									url: "/pages/login/index?form=101"
								})
							}

							// uni.showToast({
							// 	title: '登录信息已失效，请重新登录',
							// 	icon: 'none',
							// 	duration: 2000
							// })
							// setTimeout(()=>{
							// 	if (options.isLoading !== false) {
							// 		hideFullScreenLoading()
							// 	}
							// },2000)
							break
							// 其他错误，直接抛出错误提示
						default:
							if (options.isErr !== false) {

								if (res.message.length > 14) {
									uni.showModal({
										content: res.message,
										showCancel: false,
										confirmColor: '#000'
									});
								} else {
									uni.showToast({
										title: res.message,
										icon: 'none',
										duration: 2000
									})
								}

								setTimeout(() => {
									if (options.isLoading !== false) {
										hideFullScreenLoading()
									}
								}, 2000)
							}
					}
					reject(res)
				} else {
					if (options.isLoading !== false) {
						hideFullScreenLoading()
					}
					resolve(res);
				}
			},
			fail: (err) => {
				uni.showToast({
					title: err,
					icon: 'none',
					duration: 2000
				})

				setTimeout(() => {
					if (options.isLoading !== false) {
						hideFullScreenLoading()
					}
				}, 2000)
				reject(err)
			},
			// 完成之后关闭加载效果
			complete: () => {}
		})
	})
}
